﻿using Common.Device.Enums;
using Common.Device.Interfaces;
using Common.Device.Models;
using Common.Device.ViewModels;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Common.Device.Views.Devices
{
    /// <summary>
    /// DianYaCaiJiView.xaml 的交互逻辑
    /// </summary>
    public partial class DianYaCaiJiView : UserControl
    {
        public enum CheckType
        {
            None,
            Int,
            Double,
            Float
        }
        ViewModels.DianYaCaiJiViewModel viewModel = new ViewModels.DianYaCaiJiViewModel();
        public DianYaCaiJiView(DeviceEnum.DeviceModelEnum model, Order order = null)
        {
            InitializeComponent();
            DataContext = viewModel;
            enumstring = model;
            InitChannelPanel(StackPanelChannel, model, true);
            if (order != null)
            {
                //根据测试指令内容更新界面信息
                Enum.TryParse(order.temp, out DianYaCaiJiEnum.TestMode mode);
                DianYaCaiJi parameter = JsonConvert.DeserializeObject<DianYaCaiJi>(order.deviceModel);
                switch (mode)
                {
                    case DianYaCaiJiEnum.TestMode.电压采集:
                        viewModel.MenuIndex = 0;
                        foreach (var item in parameter.channels)
                        {
                            var pannel = StackPanelChannel.Children[item.channel - 1] as StackPanel;
                            (pannel.Children[0] as CheckBox).IsChecked = true;
                            (pannel.Children[1] as TextBox).Text = item.min.ToString();
                            (pannel.Children[3] as TextBox).Text = item.max.ToString();
                        }
                        //viewModel.Channel = parameter.通道;
                        //viewModel.Min = parameter.下限值?.ToString();
                        //viewModel.Max = parameter.上限值?.ToString();
                        break;
                    default:
                        break;
                }
            }
        }

        private void InitChannelPanel(StackPanel parent, DeviceEnum.DeviceModelEnum model, bool isEditView = true)
        {
            try
            {
                parent.Children.Clear();
                int num = 0;
                switch (model)
                {
                    case DeviceEnum.DeviceModelEnum.ZH_4211_14D2_30V: num = 1; break;
                    case DeviceEnum.DeviceModelEnum.ZH_44081_14M2_10V_20V: num = 8; break;
                    case DeviceEnum.DeviceModelEnum.ZH_42141_14N2_10V: num = 14; break;
                    case DeviceEnum.DeviceModelEnum.ZH_42241_14N2_30V: num = 24; break;
                    case DeviceEnum.DeviceModelEnum.ZH_42241_14N2_5V: num = 24; break;
                    case DeviceEnum.DeviceModelEnum.ZH_44121_14F2_10V_20V: num = 12; break;
                    case DeviceEnum.DeviceModelEnum.ZH_44241_14F2_30V: num = 24; break;
                    default:
                        break;
                }
                for (int i = 1; i < num + 1; i++)
                {
                    if (isEditView)
                    {
                        StackPanel panel = new StackPanel()
                        {
                            Height = 37,
                            Orientation = Orientation.Horizontal
                        };
                        CheckBox checkBox = new CheckBox()
                        {
                            Margin = new System.Windows.Thickness(0, 2.5, 0, 2.5),
                            Content = i.ToString().PadLeft(2, '0'),
                            FontSize = 15,
                            Foreground = Brushes.DodgerBlue,
                            IsChecked = false
                        };
                        HandyControl.Controls.TextBox textBox = new HandyControl.Controls.TextBox()
                        {
                            Margin = new System.Windows.Thickness(2.5, 2.5, 2.5, 2.5),
                            TextAlignment = System.Windows.TextAlignment.Right,
                            Width = 45,
                            Style = parent.FindResource("TextBoxExtend") as Style,
                        };
                        HandyControl.Controls.InfoElement.SetPlaceholder(textBox, "Min");
                        TextBlock textBlock = new TextBlock()
                        {
                            Margin = new Thickness(0, 2.5, 0, 2.5),
                            Text = "~",
                            FontSize = 16,
                            VerticalAlignment = VerticalAlignment.Center
                        };
                        HandyControl.Controls.TextBox textBox2 = new HandyControl.Controls.TextBox()
                        {
                            Margin = new System.Windows.Thickness(2.5, 2.5, 2.5, 2.5),
                            TextAlignment = System.Windows.TextAlignment.Right,
                            Width = 45,
                            Style = parent.FindResource("TextBoxExtend") as Style,
                        };
                        HandyControl.Controls.InfoElement.SetPlaceholder(textBox2, "Max");
                        TextBlock textBlock2 = new TextBlock()
                        {
                            Margin = new Thickness(0, 2.5, 0, 2.5),
                            Text = "V",
                            FontSize = 16,
                            VerticalAlignment = VerticalAlignment.Center
                        };
                        panel.Children.Add(checkBox);
                        panel.Children.Add(textBox);
                        panel.Children.Add(textBlock);
                        panel.Children.Add(textBox2);
                        panel.Children.Add(textBlock2);
                        parent.Children.Add(panel);
                    }
                    if (isEditView == false)
                    {
                        StackPanel panel = new StackPanel()
                        {
                            Height = 37,
                            Orientation = Orientation.Horizontal
                        };
                        CheckBox checkBox = new CheckBox()
                        {
                            Margin = new System.Windows.Thickness(10, 2.5, 0, 2.5),
                            Content ="通道 " + i.ToString().PadLeft(2, '0'),
                            FontSize = 15,
                            Foreground = Brushes.DodgerBlue,
                            IsChecked = false
                        };
                        panel.Children.Add(checkBox);
                        parent.Children.Add(panel);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        /// <summary>
        /// 输入检查含最大最小
        /// </summary>
        /// <param name="textBox"></param>
        /// <param name="type">检查类型</param>
        /// <param name="min">最小值</param>
        /// <param name="max">最大值</param>
        /// <returns></returns>
        public static bool TextBoxInputCheck(TextBox textBox, CheckType type, double? min = null, double? max = null)
        {
            try
            {
                if (textBox.Visibility == System.Windows.Visibility.Hidden)
                {
                    return true;
                }
                bool isRight = true;
                string input = textBox.Text.Trim();
                //输入为空
                if (input == "")
                    isRight = false;
                //输入不为空
                if (input != "")
                {
                    //不检查
                    if (type == CheckType.None)
                        isRight = true;
                    else
                    {
                        //输入值
                        double value = 0;
                        //整数检查
                        if (type == CheckType.Int)
                        {
                            isRight = int.TryParse(input, out int x);
                            value = x;
                        }
                        //双精度检查
                        else if (type == CheckType.Double)
                        {
                            isRight = double.TryParse(input, out double x);
                            value = x;
                        }
                        //单精度检擦
                        else if (type == CheckType.Float)
                        {
                            isRight = float.TryParse(input, out float x);
                            value = x;
                        }
                        //输入类型正确
                        if (isRight == true)
                        {
                            //上下限检查
                            if (min != null && max != null)
                            {
                                isRight = value >= min && value <= max;
                            }
                        }
                    }
                }
                //输入错误
                if (isRight == false)
                {
                    textBox.Focus();
                    textBox.SelectAll();
                }
                return isRight;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 选中
        /// </summary>
        /// <param name="textBox"></param>
        public static void TextBoxSelectFocus(TextBox textBox)
        {
            try
            {
                textBox.Focus();
                textBox.SelectAll();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //仪器对象
        public DeviceEnum.DeviceModelEnum enumstring;
        public object Device;
        private void ReadClick(object sender, RoutedEventArgs e)
        {
            var testModel = new ViewModels.DianYaCaiJiViewModel();
            string err = "";
            bool check = InputCheck(this.StackPanelChannel, ref testModel, ref err);
            if (check == false)
            {
                View.Controls.Dialogs.TipView.Show(err);
                return;
            }
            Models.DianYaCaiJi parameter = new Models.DianYaCaiJi()
            {
                mode = DianYaCaiJiEnum.TestMode.电压采集,
                //通道 = viewModel.Channel1,
                channels = testModel.channels,
                设备型号 = enumstring
            };
            //根据当前窗口执行对应方法
            var debug = Tool.CommonHelper.GetDebugView(this);
            if (debug != null && Device != null)
            {
                //调试功能
                Task.Run(() => parameter.GetResult(Device, null));
            }
            var edit = Tool.CommonHelper.GetEditView(this);
            if (edit != null && Device != null)
            {
                //生成指令
                edit.InsertOrder(parameter.GetOrder((Device as IDevice).Name));
            }
        }
        public static bool InputCheck(StackPanel inputModel, ref ViewModels.DianYaCaiJiViewModel testModel, ref string err)
        {
            try
            {
                for (int i = 0; i < inputModel.Children.Count; i++)
                {
                    StackPanel channel = inputModel.Children[i] as StackPanel;
                    CheckBox checkBox = channel.Children[0] as CheckBox;
                    if (checkBox.IsChecked == false)
                    {
                        continue;
                    }
                    var model = new Enums.DianYaCaiJiEnum.Channel();
                    model.channel = Convert.ToInt32(checkBox.Content.ToString().Replace("通道", ""));
                    if (channel.Children.Count > 1)
                    {
                        TextBox textBoxMin = channel.Children[1] as TextBox;
                        bool check = TextBoxInputCheck(textBoxMin, CheckType.Float);
                        if (check == false)
                        {
                            err = "输入有误";
                            return false;
                        }
                        model.min = Convert.ToSingle(textBoxMin.Text);
                        TextBox textBoxMax = channel.Children[3] as TextBox;
                        check =TextBoxInputCheck(textBoxMax, CheckType.Float);
                        if (check == false)
                        {
                            err = "输入有误";
                            return false;
                        }
                        model.max = Convert.ToSingle(textBoxMax.Text);
                        if (model.min > model.max)
                        {
                            TextBoxSelectFocus(textBoxMax);
                            err = "上下限输入有误";
                            return false;
                        }
                    }
                    testModel.channels.Add(model);
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (var item in StackPanelChannel.Children)
                {
                    StackPanel panel = item as StackPanel;
                    (panel.Children[0] as CheckBox).IsChecked = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (var item in StackPanelChannel.Children)
                {
                    StackPanel panel = item as StackPanel;
                    (panel.Children[0] as CheckBox).IsChecked = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
